'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-09-25 09:48:29
@LastEditTime: 2019-12-05 14:09:22
@LastEditors: Please set LastEditors
'''

from ...service.mongo_bill_service import MongoBillFilter
from server.pao_python.pao.service.data.mongo_db import MongoService, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status, PersonalState
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info, GetInformationByIdCard,  get_current_user_id
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...pao_python.pao.service.security.security_service import RoleService
import hashlib
import re
import datetime
import uuid
import pandas as pd
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList, get_cur_time
from ...service.constant import ApplyState
'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-08-16 11:44:34
@LastEditTime: 2019-08-16 11:44:34
@LastEditors: your name
'''
# -*- coding: utf-8 -*-

'''
服务人员函数
'''


class ServicesPersonalService(MongoService):
    ''' 服务人员 '''

    # def __init__(self, db_addr, db_port, db_name, inital_password, session):
    #     DataProcess.__init__(self, db_addr, db_port, db_name)
    #     self.db_name = db_name
    #     self.inital_password = inital_password
    #     self.session = session
    #     self.role_service = RoleService(
    #         db_addr, db_port, db_name, inital_password, session)
    #     self.bill_manage_service = BillManageService(
    #         db_addr, db_port, db_name, inital_password, session)
    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_server = BillManageService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd, self.inital_password, self.session)

    def get_service_personal_list(self, condition, page, count):
        '''获取待审核服务人员列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        if 'date_range' in condition.keys():
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ['id', 'servicer_name', 'servicer_sex',
                'servicer_id_card', 'start_date', 'end_date']
        persion_id = get_current_user_id(self.session)
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_Approval_Process', 'id', 'business_id', 'process')\
            .add_fields({'new_field': self.ao.array_filter(
                "$process", "aa", ((F('$aa.approval_user_id') == persion_id) & (F('$aa.step_no') == (F('step_no'))) & (F('$aa.status') == '待审批')).f)}).match((C("new_field") != None) & (C("new_field") != []))\
            .match_bill((C('register_date') >= as_date(values['start_date']))
                        & (C('register_date') <= as_date(values['end_date']))
                        & (C('id') == values['id'])
                        & (C('servicer_name').like(values['servicer_name']))
                        & (C('servicer_sex') == values['servicer_sex'])
                        & (C('servicer_id_card') == values['servicer_id_card']))\
            .project({'_id': 0, 'new_field._id': 0, 'process._id': 0})
        res = self.page_query(
            _filter, 'PT_Service_Personal', page, count)
        if res['result']:
            for result in res['result']:
                print('>>>>>>>>>>>>>>>>>', result)
                if result.get('servicer_id_card'):
                    if len(result.get('servicer_id_card')) == 18:
                        get_infomation_by_idcard = GetInformationByIdCard(
                            result.get('servicer_id_card'))
                        result['age'] = get_infomation_by_idcard.get_age()
        return res

    def update_service_personal_apply(self, service_personal_apply):
        '''# 服务人员申请'''
        res = 'Fail'

        # 根据身份证以及姓名判断这个用户是否存在资料
        print(service_personal_apply)
        _filter = MongoBillFilter()
        _filter.match_bill((C('name') == service_personal_apply['servicer_name'])
                           & (C('id_card') == service_personal_apply['servicer_id_card']))\
            .project({'_id': 0})
        user_res = self.query(_filter, 'PT_User')
        print("结果>>>>>>>>", user_res)
        if len(user_res) > 0:
            # 查询是否已经存在申请记录
            _filter = MongoBillFilter()
            _filter.match_bill((C('servicer_id') == user_res[0]['id'])
                               & (C('step_no') != -1))\
                .project({'_id': 0})
            record_res = self.query(_filter, 'PT_Service_Personal')
            print(22222222222222222222222222222222222222222222)
            if len(record_res) > 0:
                res = '该用户已经申请过了，不可重复申请'
            else:
                print(33333333333333333333333333333333333)
                data_info = get_info(service_personal_apply, self.session)
                # 根据审批定义新增审核过程表数据，新增业务表数据
                _filter = MongoBillFilter()
                _filter.match_bill((C('approval_type') == 'ServicePersonalApply'))\
                    .project({'_id': 0})
                res_define = self.query(_filter, 'PT_Approval_Define')
                print(4444444444444444444444444)
                if len(res_define) > 0 and len(res_define[0]['approval_list']) > 0:
                    for approval in res_define[0]['approval_list']:
                        if approval['step_no'] == 1:
                            process_data_list = []
                            # 查找属于平台的组织结构
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('personnel_type') == '2') & (C('organization_info.personnel_category') == '平台'))\
                                .project({'_id': 0})
                            forumInfo = self.query(_filter, 'PT_User')
                            print(forumInfo)
                            # 拿到平台的id以及角色id确定可以审核的人id
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == forumInfo[0]['id']))\
                                .project({'_id': 0})
                            aboutUserIdList = self.query(
                                _filter, 'PT_Set_Role')
                            approval_user_id = aboutUserIdList[0]['principal_account_id']
                            process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                            approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                            process_data_list.append(
                                get_info(process_data, self.session))
                            data_info['step_no'] = process_data_list[0]['step_no']
                            data_info['status'] = ApplyState.apply
                            data_info['register_date'] = get_cur_time()
                            data_info['servicer_id'] = user_res[0]['id']
                            data = [data_info, process_data_list]
                            bill_id = self.bill_manage_server.add_bill(
                                OperationType.add.value, TypeId.servicePersonal.value, data, ['PT_Service_Personal', 'PT_Approval_Process'])
                            if bill_id:
                                res = 'Success'
                        if approval['step_no'] == 2:
                            process_data_list = []
                            # 根据申请人的信息去user表查所属行政区划id
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('id') == user_res[0]['id']))\
                                .project({'_id': 0})
                            userInfo = self.query(_filter, 'PT_User')
                            # 根据行政区划id找出当前区划下的民政机构
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('admin_area_id') == userInfo[0]['admin_area_id']) & (C('personnel_type') == '2') & (C('organization_info.personnel_category') == '民政'))\
                                .project({'_id': 0})
                            mzOrganizationInfo = self.query(_filter, 'PT_User')
                            # 根据角色id以及机构id找出审核人id
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == mzOrganizationInfo[0]['id']))\
                                .project({'_id': 0})
                            aboutUserIdList = self.query(
                                _filter, 'PT_Set_Role')
                            approval_user_id = aboutUserIdList[0]['principal_account_id']
                            # print("长者33333333333333333333333333333333333333333333",approval_user_id)
                            process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                            approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                            process_data_list.append(
                                get_info(process_data, self.session))
                            data = [process_data_list]
                            bill_id = self.bill_manage_server.add_bill(
                                OperationType.add.value, TypeId.servicePersonal.value, data, ['PT_Approval_Process'])
                            if bill_id:
                                res = 'Success'
        else:
            res = '该用户不存在，请先注册'
        return res
        # def process_func(db):
        #     nonlocal res
        #     if 'id' in service_personal_apply.keys():
        #         bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
        #                                                     TypeId.servicePersonal.value, service_personal_apply, 'PT_Service_Personal')
        #         if bill_id:
        #             res = 'Success'
        #     else:
        #         service_personal_apply['register_date'] = get_cur_time()
        #         bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
        #                                                     TypeId.servicePersonal.value, service_personal_apply, 'PT_Service_Personal')
        #         if bill_id:
        #             res = 'Success'
        # process_db(self.db_addr, self.db_port, self.db_name, process_func)
        # return res

    def subsidy_service_personal_apply(self, reviewed_result):
        '''# 服务人员审核'''
        res = 'Fail'

        persion_id = get_current_user_id(self.session)
        print(reviewed_result)
        if 'id' in reviewed_result.keys():
            # 查询记录表的记录
            _filter = MongoBillFilter()
            _filter.match_bill((C('id') == reviewed_result['id']))\
                .project({'_id': 0})
            apply_record = self.query(_filter, 'PT_Service_Personal')
            print(111111111111111111111)
            if len(apply_record) > 0:
                jlb_record = apply_record[0]
                # 查询过程表的数据
                _filter_process = MongoBillFilter()
                _filter_process.match_bill((C('business_id') == reviewed_result['id']) & (
                    C('approval_user_id') == persion_id) & (C('step_no') == jlb_record['step_no'])).project({'_id': 0})
                process_data = self.query(
                    _filter_process, 'PT_Approval_Process')
                if len(process_data) > 0 and 'subsidy_res' in reviewed_result.keys() and 'opinion' in reviewed_result.keys():
                    # 获取审批结果
                    subsidy_result = reviewed_result['subsidy_res']
                    process = process_data[0]
                    process['opinion'] = []
                    process['opinion'].append(reviewed_result['opinion'])
                    if subsidy_result == '通过':
                        process['status'] = '通过'
                        # 判断是否最后一步，最后一步则完结业务单据状态且step_no改为空,不是最后一步则把step_no改为下一步
                        _filter_process_length = MongoBillFilter()
                        _filter_process_length.match_bill(
                            (C('business_id') == reviewed_result['id'])).project({'_id': 0})
                        process_data_length = len(self.query(
                            _filter_process_length, 'PT_Approval_Process'))
                        if jlb_record['step_no'] > 0 and process_data_length == jlb_record['step_no']:
                            # 最后一步
                            jlb_record['status'] = '通过'
                            jlb_record['step_no'] = -1
                            # 将申请人的信息修改为工作人员，并绑上组织机构id
                            # 拿到用户的姓名以及身份证去user表找到该用户
                            user_name = jlb_record['servicer_name']
                            id_card = jlb_record['servicer_id_card']
                            _filter = MongoBillFilter()
                            _filter.match_bill((C('name') == user_name)
                                               & (C('id_card') == id_card))\
                                .project({'_id': 0})
                            user_info_res = self.query(_filter, 'PT_User')
                            print(111111)
                            # 将这个人的身份更改为工作人员
                            user_info = user_info_res[0]
                            user_info['personnel_info']['personnel_category'] = '工作人员'
                            # 绑定组织机构id
                            user_info['organization_id'] = jlb_record['servicer_organization_id']
                            bill_id = self.bill_manage_server.add_bill(OperationType.update.value,
                                                                       TypeId.servicePersonal.value, user_info, 'PT_User')
                            if bill_id:
                                res = 'Success'
                        elif jlb_record['step_no'] > 0 and process_data_length > jlb_record['step_no']:
                                # 非最后一步
                            jlb_record['status'] = '审批中'
                            jlb_record['step_no'] = jlb_record['step_no'] + 1
                        else:
                            return '无法重复审批'
                    if subsidy_result == '不通过':
                        process['status'] = '不通过'
                        # 把业务单据的状态改为不通过
                        jlb_record['status'] = '不通过'
                    # 修改业务表和过程表
                    data = [jlb_record, process]
                    bill_id = self.bill_manage_server.add_bill(OperationType.update.value, TypeId.servicePersonal.value, data, [
                        'PT_Service_Personal', 'PT_Approval_Process'])
                    if bill_id:
                        res = 'Success'
        return res

    def update_service_personal(self, service_personal):
        '''# 新增/修改服务人员'''
        res = 'Fail'
        service_personal['state'] = PersonalState.inReview.value

        def process_func(db):
            nonlocal res
            if 'id' in service_personal.keys():
                bill_id = self.bill_manage_server.add_bill(OperationType.update.value,
                                                           TypeId.servicePersonal.value, service_personal, 'PT_Service_Personal')
                if bill_id:
                    res = 'Success'
            else:
                service_personal['register_date'] = get_cur_time()
                bill_id = self.bill_manage_server.add_bill(OperationType.add.value,
                                                           TypeId.servicePersonal.value, service_personal, 'PT_Service_Personal')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def delete_service_personal(self, service_personal_ids):
        '''删除服务人员接口

        Arguments:
            service_personal_ids   {ids}      数据id
        '''
        res = 'fail'

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(service_personal_ids, str):
                ids.append(service_personal_ids)
            else:
                ids = service_personal_ids
            for service_personal_id in ids:
                # 查询被删除的数据信息
                data = find_data(db, 'PT_Service_Personal', {
                    'id': service_personal_id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    bill_id = self.bill_manage_server.add_bill(OperationType.delete.value,
                                                               TypeId.servicePersonal.value, data[0], 'PT_Service_Personal')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_work_people_statistics(self, condition):
        # 查出所有的辛福院
        _filter = MongoBillFilter()
        _filter.match_bill((C('personnel_type') == '2') & (C('organization_info.personnel_category') == '幸福院'))\
            .add_fields({'xfy_name': '$name'})\
            .lookup_bill('PT_Administration_Division', 'admin_area_id', 'id', 'area')\
            .add_fields({'parent_id': '$area.parent_id'})\
            .lookup_bill('PT_Administration_Division', 'parent_id', 'id', 'parent_area')\
            .add_fields({
                'shequ': '$area.name',
                'zhenjie': '$parent_area.name',
            })\
            .inner_join_bill('PT_Set_Role', 'id', 'role_of_account_id', 'people_list')\
            .inner_join_bill('PT_User', 'people_list.principal_account_id', 'id', 'user')\
            .add_fields({'user_id': '$user.id'})\
            .match_bill((C('user.personnel_type') == '1') & (C('user.personnel_info.personnel_category') == '工作人员') | (C('user.personnel_info.personnel_category') == '平台管理员'))\
            .add_fields({
                'work_people_man': self.ao.switch([self.ao.case(((F('user.personnel_info.sex') == '男')), 1)], 0),
                'work_people_women': self.ao.switch([self.ao.case(((F('user.personnel_info.sex') == '女')), 1)], 0),
                'work_people_guanli': self.ao.switch([self.ao.case(((F('user.personnel_info.worker_category') == '管理人员')), 1)], 0),
                'work_people_zhuanye': self.ao.switch([self.ao.case(((F('user.personnel_info.worker_category') == '专业技能人员')), 1)], 0),
                'work_people_shegong': self.ao.switch([self.ao.case(((F('user.personnel_info.worker_category') == '社工人员')), 1)], 0),
                'work_people_houqin': self.ao.switch([self.ao.case(((F('user.personnel_info.worker_category') == '后勤人员')), 1)], 0),
                'work_people_yigongdui': self.ao.switch([self.ao.case(((F('user.personnel_info.worker_category') == '义工服务队')), 1)], 0),
                'work_people_yigong': self.ao.switch([self.ao.case(((F('user.personnel_info.worker_category') == '义工')), 1)], 0),
            })\
            .project({'_id': 0, 'area._id': 0, 'parent_area._id': 0, 'people_list._id': 0, 'user._id': 0})\
            .group(
                {
                    'xfy_name': '$xfy_name',
                    'shequ': '$area.name',
                    'zhenjie': '$parent_area.name', 
                },
                [{
                    'man_num': self.ao.summation('$work_people_man')
                }, 
                {
                    'women_num': self.ao.summation('$work_people_women')
                },
                {
                    'guanli_num': self.ao.summation('$work_people_guanli')
                },
                {
                    'zhuanye_num': self.ao.summation('$work_people_zhuanye')
                },
                {
                    'shegong_num': self.ao.summation('$work_people_shegong')
                },
                {
                    'houqin_num': self.ao.summation('$work_people_houqin')
                },
                {
                    'yigongdui_num': self.ao.summation('$work_people_yigongdui')
                },
                {
                    'yigong_num': self.ao.summation('$work_people_yigong')
                },
                {
                    'work_people_all': self.ao.summation(1)
                }])\

        work_list = self.query(_filter, 'PT_User')
        return work_list
